<template>
    <div class="dhzn_goodsactivity">
        <!-- 活动 -->
        <div class="dg_m-content" v-if="pageingstate !== 2">
            <!-- 查询 -->
            <div class="dh_m-c-query mb10">
                <el-form :model="selectqurey" label-width="72px" ref="selectqurey" :rules="rules" inline size='mini' class="dh_mcq-form">
                    <el-form-item label="活动类型" prop='type'>
                        <el-select v-model="selectqurey.type" clearable>
                            <el-option label="满减活动" value="0"></el-option>
                            <el-option label="包邮活动" value="1"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="requestquery('selectqurey'),currentPage=1,pageingstate=1">查询</el-button>
                        <el-button type="danger" @click="abolish('selectqurey'),currentPage=1,goodsActivity(),pageingstate=0">取消</el-button>
                    </el-form-item>
                </el-form>
                <span class="bc4a wh br5 f14 p5" @click="pageingstate = 2">添加活动</span>
            </div>

            <!-- 数据列表 -->
            <div class="dh_m-c-list f14">
                <!-- 数据表 -->
                <table class="dh_mcl-tabel tc">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>活动商品</th>
                            <th>活动类型</th>
                            <th>触发条件</th>
                            <th>减免范围</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-for="(item,key) in basiclist" :key="key">
                            <td>{{item.id}}</td>
                            <td>{{item.goodsid}}</td>
                            <td>{{item.type | filtertype}}</td>
                            <td><span class="ff53">满{{item.full}}</span></td>
                            <td><span v-if="item.type == 1">包邮</span><span v-else class="ff53">减{{item.reduce}}</span></td>
                            <td>
                                <button type="button" class="wh bc4a br5 pt5 pb5" @click="dialogstate=true;for(var i in activityupdate)activityupdate[i]=item[i],activityupdate.key=key"><i class="el-icon-edit-outline"></i>修改</button>
                                <button type="button" class="wh bcfd br5 pt5 pb5" @click="requestdelete(item.id,key)">删除<i class="el-icon-delete"></i></button>
                            </td>
                        </tr>
                    </tbody>
                </table>

                <div class="d_rj-block mt20">
                    <el-pagination
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="currentPage"
                        :page-size="pagesize"
                        layout="total, prev, pager, next, jumper"
                        :total="total">
                    </el-pagination>
                </div>
            </div>
            <!-- 弹出层 -->
            <el-dialog title="修改活动信息" :visible.sync="dialogstate" width="400px" center>
                <el-form :model="activityupdate" label-width="80px" class="dg_mc-dialog-form">
                    <el-form-item :label="activityupdate.type===0 ? '满减条件' : '包邮条件'">
                        <el-input v-model="activityupdate.full" placeholder="请输入新的触发条件"></el-input>
                    </el-form-item>

                    <el-form-item label="满减金额" v-show="activityupdate.type===0">
                        <el-input v-model="activityupdate.reduce" placeholder="请输入新的活动力度"></el-input>
                    </el-form-item>
                </el-form>
                <span slot="footer">
                    <el-button @click="dialogstate = false">取 消</el-button>
                    <el-button type="primary" @click="requestupdate">确 定</el-button>
                </span>
            </el-dialog>
        </div>
        <!-- 添加模块 -->
        <div class="dg_m-add" v-else>
            <div class="dg_m-a-title bb1 mb10"><span class="wh bc4a dib br5 p5 mb10 f14" @click="pageingstate = 0">返回列表</span></div>
            <div class="dg_m-a-content">
                <el-form :model="activityadd" label-width="80px" ref="activityadd" :rules="rules" class="dg_mac-form">
                    <el-form-item label="活动类型" prop="type">
                        <el-select v-model="activityadd.type" clearable @change="activityadd.full='',activityadd.reduce=''">
                            <el-option label="满减活动" value="0"></el-option>
                            <el-option label="包邮活动" value="1"></el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="触发条件" prop="full">
                        <el-col :span="6"><el-input v-model='activityadd.full' placeholder="请输入触发活动的条件" clearable></el-input></el-col>
                    </el-form-item>

                    <el-form-item label="活动力度" prop="reduce" v-if="activityadd.type === '0'">
                        <el-col :span="6"><el-input v-model="activityadd.reduce" placeholder="请输入满足条件后活动减免多少" clearable></el-input></el-col>
                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" @click="requestadd('activityadd'),pageingstate = 0">添加</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>
    </div>
</template>

<script>
let axios = require('axios')
export default {
    components: {},
    data() {
        return {
            id: '',                             //路由传值
            token: '',                          //身份验证
            pageingstate: 0,                    //页面切换分页运行函数的状态管理
            basiclist: [],
            // 查询条件绑定对象
            selectqurey: {
                type:''
            },
            // 修改字段绑定对象
            activityupdate:{
                id: '',
                type: '',
                full: '',
                reduce: '',
            },
            // 添加字段绑定对象
            activityadd:{
                type: '',
                full: '',
                reduce: '',
            },
            // 输入验证
            rules:{
                type:[
                    {required:true,message:'请选择活动类型',trigger:'change'}
                ],
                full:[
                    {required:true,message:'请输入触发条件',trigger:'change'}
                ],
                reduce:[
                    {required:true,message:'请输入活动力度',trigger:'change'}
                ],
            },
            dialogstate: false,                 //弹出层状态
            currentPage: 1,						//分页的默认页数
            pagesize: 10,                       //单页条数
            total: 0,						   //总条数
        };
    },
    filters:{
        filtertype(type){
            if(type === 0){
                type = '满减'
            }else{
                type = '包邮'
            }
            return type
        }
    },
    computed: {},
    watch: {},
    methods: {
        // 单页条数
        handleSizeChange(val) {
            // console.log(`每页: ${val}条数据`);
            let that = this;
            that.pagesize = val;
            if(that.pageingstate === 0){
                that.goodsActivity()
            }else{
                that.requestquery('selectqurey')
            }
        },

        //分页的跳页函数
        handleCurrentChange(val) {
            // console.log(`当前页: ${val}`);
            let that = this;
            that.currentPage = val;
            if(that.pageingstate === 0){
                that.goodsActivity()
            }else{
                that.requestquery('selectqurey')
            }
        },

        // 添加活动
        requestadd(add){
            let that = this;
            that.$refs[add].validate((valid)=>{
                if(valid){
                    let data = {goodsid:that.id};
                    for(var i in that.activityadd) data[i] = that.activityadd[i];
                    let updata = JSON.stringify(data);
                    console.log(updata,data)
                    axios({
                        method: 'post',
                        url: '/api/goodsActivity/add',
                        headers: {
                            'Content-Type': 'application/json',
                            'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                        },
                        data: updata
                    }).then( resp=>{ 
                        console.log(resp)
                        data.id = resp.data.data;
                        that.basiclist.length < that.pagesize ? that.basiclist.push(data) : '';
                        that.total += 1;
                        for(var u in that.activityadd) that.activityadd[u] = "";
                    }).catch( err=> {console.log(err)})
                }else{return}
            })
        },

        // 删除活动
        requestdelete(id,key){
            let that = this;
            let updata = JSON.stringify({id: id});
            that.$confirm('此操作将永久删除该文件, 是否继续?', '提示',{
                confirmButtonText:'确定',
                cancelButtonText: '取消',
                type: 'warning',
                center: true
            }).then(()=>{
                axios({
                    method: 'post',
                    url: '/api/goodsActivity/delete',
                    headers: {
                        'Content-Type': 'application/json',
                        'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                    },
                    data: updata
                }).then( resp=> {
                    console.log(resp)
                    if(resp.data.data === '删除成功！'){
                        that.basiclist.splice(key,1);
                        that.total--
                    }
                }).catch( err=> {console.log(err)})

                this.$message({
                    type: 'success',
                    message: '删除成功'
                })
            }).catch(()=>{
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                })
            })
        },

        // 修改活动
        requestupdate(){
            let that = this;
            that.dialogstate = false
            let data = {};
            // console.log(that.activityupdate)
            for(var o in that.activityupdate) o!=='key' && that.activityupdate[o] !== null ? data[o] = that.activityupdate[o] : '';
            let updata = JSON.stringify(data)
            // console.log(data,updata)
            axios({
                method: 'post',
                url: '/api/goodsActivity/update',
                headers: {
                    'Content-Type': 'application/json',
                    'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                },
                data: updata
            }).then( resp=> {
                console.log(resp)
                let key = that.activityupdate.key
                for(var u in data) that.basiclist[key][u] === data[u] ? '' : that.basiclist[key][u] = data[u];
            }).catch( err=> {console.log(err)})
        },

        // 活动
        goodsActivity(){
            let that = this;
            let data = {current: that.currentPage,size:that.pagesize,goodsid: that.id};
            let updata = JSON.stringify(data);
            axios({    
                method: 'post',
                url: '/api/goodsActivity/list',
                headers: {
                    'Content-Type': 'application/json',
                    'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                },
                data: updata
            }).then( resp=> { 
                console.log('活动',resp)
                that.basiclist = resp.data.data;
                that.total = resp.data.code;
            }).catch( err=>{console.log(err)})
        },

        // 查找
        requestquery(query){
            let that = this;
            that.$refs[query].validate((valid)=>{
                if(valid){
                    let data = {current:that.currentPage,size:that.pagesize,goodsid: that.id,type:that.selectqurey.type};
                    let updata = JSON.stringify(data)
                    console.log(data,updata)
                    axios({    
                        method: 'post',
                        url: '/api/goodsActivity/list',
                        headers: {
                            'Content-Type': 'application/json',
                            'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                        },
                        data: updata
                    }).then( resp=> { 
                        console.log('活动',resp)
                        that.basiclist = resp.data.data;
                        that.total = resp.data.code;
                    }).catch( err=>{console.log(err)})
                }else{return}
            })
        },
        // 取消查询
        abolish(query){
            this.$refs[query].resetFields()
        },

        
        //拿token
        newtoken(){
            let that = this;
            let axios = require('axios')
			let loguser = JSON.parse(sessionStorage.getItem('updata'))
			let data = {username:loguser.username, password:loguser.password};
			let updata = JSON.stringify(data);
			axios({
				method: 'post',
				url: '/api/getAuthority/manager',
				headers: { 'Content-Type': 'application/json' },
				data: updata
			})
			.then( resp=> {
                that.token = resp.data.data;
				sessionStorage.setItem("token", JSON.stringify(resp.data.data))
                that.goodsActivity()
			}).catch( err=> {})
        }
    },
    created() {},
    mounted() {
        let that = this;
        that.id = that.$route.params.aid;
        that.newtoken()
    },
    beforeCreate() {},
    beforeMount() {},
    beforeUpdate() {},
    updated() {},
    beforeDestroy() {},
    destroyed() {},
    activated() {},
    }
</script>
<style scoped>
.dhzn_goodsactivity{
    height: calc(100% - 51px);
}
/* 内容查询、列表和分页 */
.dg_m-content{
    height: 100%;
}
/* 查询 */
.dh_m-c-query{
    display: flex;
    justify-content: space-between;
}
.dh_mcq-form .el-form-item--mini.el-form-item, .el-form-item--small.el-form-item{
    margin: 0;
}
/* 表单 */
.dh_m-c-list{
    display: flex;
    flex-wrap: wrap;
    height: calc(100% - 47px);
}
.dh_mcl-tabel{
    width: 100%;
    color: #666666;
    border-collapse: collapse;
    border-top: 1px solid #e0e0e0;
    border-right: 1px solid #e0e0e0;
}
.dh_mcl-tabel thead tr, .dh_mcl-tabel tbody tr:hover{
    background-color: #F2F2F2;
}
.dh_mcl-tabel tr th,.dh_mcl-tabel tr td{
    height: 50px;
    border-bottom: 1px solid #e0e0e0;
    border-left: 1px solid #e0e0e0;
}
.dh_mcl-tabel tr td img{
    max-width: 120px;
    max-height: 80px;
}
.d_rj-block{
    margin-top: auto;
}
</style>